package cn.itcast.web.action;

import cn.itcast.domain.base.Area;
import cn.itcast.domain.base.SubArea;
import cn.itcast.web.action.common.BaseAction;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.convention.annotation.*;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Namespace("/")
@ParentPackage("struts-default")
@Controller
@Scope("prototype")
@Actions
public class SubAreaAction extends BaseAction<SubArea> {

    private File file;//接收传入的Excel文件
    private String fileFileName;//文件名

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public void setFile(File file) {
        this.file = file;
    }

    //    action : '../../subarea_batchImport.action',
     @Action(value = "subarea_batchImport",results = {@Result(name = "success",location = "./pages/base/sub_area.html",type = "redirect")})
    public String batchImport() throws IOException {
   //对Excel文件名后缀进行判断
         Workbook workbook=null;
         if(fileFileName.endsWith(".xlsx")){
          workbook= new XSSFWorkbook(new FileInputStream(file));//07版本以后
         }
         workbook=new HSSFWorkbook(new FileInputStream(file));//07 版本以前
         //读取sheet
         Sheet sheet = workbook.getSheetAt(0);
         //遍历sheet每一行
         for(Row row :sheet){
             //去掉首尾无效数据
             if(row.getRowNum()==0){
                 continue;
             }
             if (row.getCell(0)==null||StringUtils.isBlank(row.getCell(0).getStringCellValue())){
                 continue;
             }
             //封装有效数据  分拣编号	 省	市	区	关键字	起始号	终止号	单双号	辅助关键字	定区编号
           Area area=  new Area();
//             subArea.setFixedArea(row.getCell(0).getStringCellValue());
             String province=(row.getCell(1).getStringCellValue());
             area.setProvince(province);
             String city=(row.getCell(2).getStringCellValue());
             area.setCity(city);
             String district=(row.getCell(3).getStringCellValue());
             area.setDistrict(district);
             model.setArea(area);
             model.setKeyWords(row.getCell(4).getStringCellValue());
             model.setStartNum(row.getCell(5).getStringCellValue());
             model.setEndNum(row.getCell(6).getStringCellValue());
//             subArea.setSingle(row.getCell(7).getStringCellValue());
             model.setKeyWords(row.getCell(8).getStringCellValue());
             model.setId(row.getCell(9).getStringCellValue());

           //save(model);


         }
         return SUCCESS;
    }
}
